package com.cherry.androidcode.util

import android.os.Build
import android.os.Environment
import java.io.File
import java.io.FileInputStream
import java.lang.reflect.Method
import java.util.*
import android.text.TextUtils




/**
 * @author DongMS
 * @date 2019/7/2
 */
object DeviceUtil {

    private const val KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name"
    private const val KEY_FLYME_VERSION_NAME = "ro.build.display.id"
    private val MEIZUBOARD = arrayOf("m9", "M9", "mx", "MX")
    private  const val FLYME = "flyme"

    private val sMiuiVersionName by lazy {
        getPhoneSystemVersionName(KEY_MIUI_VERSION_NAME)
    }
    private val sFlymeVersionName by lazy {
        getPhoneSystemVersionName(KEY_FLYME_VERSION_NAME)
    }

    private fun getPhoneSystemVersionName(versionName: String): String? {
        var fileInputStream: FileInputStream? = null
        return try {
            fileInputStream = FileInputStream(File(Environment.getRootDirectory(), "build.prop"))
            val properties = Properties()
            properties.load(fileInputStream)
            val clzSystemProperties = Class.forName("android.os.SystemProperties")
            val getMethod = clzSystemProperties.getDeclaredMethod("get", String::class.java)
            getLowerCaseName(properties, getMethod, versionName)

        } catch (e: Exception) {
            e.printStackTrace()
            null
        } finally {
            //try..catch...finally 有return语句以finally的为准，不管是try块还是catch块中的return
            fileInputStream?.close()
        }
    }


    /**
     * 判断是否为魅族
     */
    fun isMeizu(): Boolean {
        return isPhone(MEIZUBOARD) || isFlyme()
    }

    /**
     * 判断是否是flyme系统
     */
    fun isFlyme(): Boolean {
        return !TextUtils.isEmpty(sFlymeVersionName) && sFlymeVersionName!!.contains(FLYME)
    }

    /**
     * 判断是否为小米
     */
    fun isXiaomi(): Boolean {
        return Build.BRAND.toLowerCase().contains("xiaomi") || isMIUI()
    }

    /**
     * 判断是否是MIUI系统
     */
    fun isMIUI(): Boolean {
        return !TextUtils.isEmpty(sMiuiVersionName)
    }

    private fun isPhone(boards: Array<String>): Boolean {
        val board = Build.BOARD ?: return false
        return !boards.find { board == it }.isNullOrEmpty()
    }

    private fun getLowerCaseName(p: Properties, get: Method, key: String): String? {
        var name = p.getProperty(key)
        if (name == null) {
            try {
                name = get.invoke(null, key) as? String
            } catch (ignored: Exception) {
            }
        }
        if (name != null) {
            name = name.toLowerCase()
        }
        return name
    }
}